
import socket
import threading
import time

def test_connection(port, message, client_id):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(('localhost', port))
        s.sendall(message.encode())
        data = s.recv(1024)
        print(f"Client {client_id} received: {data.decode()}")
        s.close()
    except Exception as e:
        print(f"Client {client_id} error: {str(e)}")

def run_tests():
    # 测试基础连接
    print("Testing basic connection...")
    test_connection(9999, "Hello Server!", 1)
    
    # 测试多客户端
    print("\nTesting multiple clients...")
    threads = []
    for i in range(2, 5):
        t = threading.Thread(target=test_connection, 
                           args=(9999+i, f"Message from client {i}", i))
        threads.append(t)
        t.start()
    
    for t in threads:
        t.join()

if __name__ == "__main__":
    print("Starting server tests...")
    run_tests()
    print("\nTests completed!")
